package com.masterclient.app.modules.shop.contract;

import com.eoner.baselib.container.CommonBaseResponse;
import com.eoner.baselib.presenter.ThrowableConsumer;
import com.masterclient.app.httpservice.RetrofitUtil2;
import com.masterclient.app.modules.shop.beans.StockDetailsBean;
import com.masterclient.app.modules.shop.beans.StockExplainBean;
import org.json.JSONException;
import org.json.JSONObject;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;

public class StockDetailsPresenter extends StockDetailsContract.Presenter {

    @Override
    public void getStockList(String productId) {
        mRxManager.add(toSubscribe(RetrofitUtil2.getInstance().getStockList(productId), (Consumer<CommonBaseResponse<StockDetailsBean>>) bean -> {
            if(bean.getCode() == 0){
                mView.showData(bean.getData());
            }else {
                mView.showDataFailed(bean.getMsg());
            }
        },new ThrowableConsumer() {
            @Override
            public void accept(Throwable o) throws Exception {
                mView.showDataFailed("网络异常，请重试");
                super.accept(o);
            }
        }));
    }

    @Override
    public void getExplain() {
        mRxManager.add(toSubscribe(RetrofitUtil2.getInstance().getExplain(), (Consumer<CommonBaseResponse<StockExplainBean>>) bean -> {
            if(bean.getCode() == 0){
                mView.showExplainData(bean.getData());
            }else {
                mView.showExplainFailed(bean.getMsg());
            }
        },new ThrowableConsumer() {
            @Override
            public void accept(Throwable o) throws Exception {
                mView.showExplainFailed("网络异常，请重试");
                super.accept(o);
            }
        }));
    }

    @Override
    public void updateStockNum(String sku_id,String quantity,String remark,String origin_quantity) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("sku_id",sku_id);
            jsonObject.put("quantity",quantity);
            jsonObject.put("remark",remark);
            jsonObject.put("origin_quantity",origin_quantity);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        mRxManager.add(toSubscribe(RetrofitUtil2.getInstance().updateStockNum(body), (Consumer<CommonBaseResponse>) bean -> {
            if(bean.getCode() == 0){
                mView.updateSuccess();
            }else {
                mView.updateFailed(bean.getMsg());
            }
        }, new ThrowableConsumer(){
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.updateFailed("网络异常，请重试");
            }
        }));
    }
}
